#!/bin/bash

#
#	Copyright (C) 2014  Julio Montes, Mario Carrillo
#	
#	Julio Montes e-mail: imc.coder@gmail.com 
#
#	Mario Carrillo e-mail: mario_90ago@live.com.mx
#
#	BSD 3-Clause License
#

WORK_DIR=${PWD}
CB_PROJECT=ideall.cbp

#default values
export WX_INSTALLED=1
export MAKEFILES=0
export CODEBLOCKS=1
export GENERATOR_NAME="CodeBlocks - Unix Makefiles"

function get_wx_include_dirs()
{
	TOKENS=(`wx-config --cflags`)
	for element in $(seq 0 $((${#TOKENS[@]} - 1)))
	do
		if [[ ${TOKENS[$element]} == -I* ]];then
			export WX_INCLUDE_DIRS="${TOKENS[$element]:2};${WX_INCLUDE_DIRS}"
		fi
	done
}

function set_directories()
{
	if [ $MAKEFILES == 1 ] && [ $WX_INSTALLED == 1 ];then
		export DEBUG_DIR=${WORK_DIR}/makefiles/debug
		export RELEASE_DIR=${WORK_DIR}/makefiles/release
	elif [ $CODEBLOCKS == 1 ] && [ $WX_INSTALLED == 1 ];then
		export DEBUG_DIR=${WORK_DIR}/codeblocks/debug
		export RELEASE_DIR=${WORK_DIR}/codeblocks/release
	else
		echo "error: unknown project"
		exit 1
	fi
	
	mkdir -p ${DEBUG_DIR} ${RELEASE_DIR}
}

function process_args()
{
	for arg in "$@"
	do
		case $arg in
			--makefiles )
				export MAKEFILES=1
				export CODEBLOCKS=0
				export GENERATOR_NAME="Unix Makefiles"
			;;
	
			--codeblocks )
				export CODEBLOCKS=1
				export MAKEFILES=0
				export GENERATOR_NAME="CodeBlocks - Unix Makefiles"
			;;
	
			* )
				echo "error: unknown option"
				exit 1
			;;
		esac
	done
}

function gen_project()
{
	cd ${DEBUG_DIR}
	cmake -G "${GENERATOR_NAME}" -DCMAKE_BUILD_TYPE=DEBUG -DWX_INSTALLED=${WX_INSTALLED} -DWX_INSTALLED_INCLUDE_DIRS="${WX_INCLUDE_DIRS}" ${WORK_DIR}
	cd ${WORK_DIR}

	cd ${RELEASE_DIR}
		cmake -G "${GENERATOR_NAME}" -DCMAKE_BUILD_TYPE=RELEASE -DWX_INSTALLED=${WX_INSTALLED} -DWX_INSTALLED_INCLUDE_DIRS="${WX_INCLUDE_DIRS}" ${WORK_DIR}
	cd ${WORK_DIR}
}

function fix_codeblocks()
{
	#fix jobs in codeblocks
	sync
	sed -i 's/\/make/\/make -j'`nproc`'/g' ${DEBUG_DIR}/${CB_PROJECT}
	sed -i 's/\/make/\/make -j'`nproc`'/g' ${RELEASE_DIR}/${CB_PROJECT}

	#fix to change the working directory
	SED_WORK_DIR=`echo ${WORK_DIR} | sed 's/\//\\\\\//g'`
	SED_CB_DEBUG_DIR=`echo ${DEBUG_DIR} | sed 's/\//\\\\\//g'`
	SED_CB_RELEASE_DIR=`echo ${RELEASE_DIR} | sed 's/\//\\\\\//g'`
	sed -i 's/working_dir=\"'${SED_CB_DEBUG_DIR}'/working_dir=\"'${SED_WORK_DIR}'/g' ${DEBUG_DIR}/${CB_PROJECT}
	sed -i 's/working_dir=\"'${SED_CB_RELEASE_DIR}'/working_dir=\"'${SED_WORK_DIR}'/g' ${RELEASE_DIR}/${CB_PROJECT}
}

function fix_projects()
{
	if [ $CODEBLOCKS == 1 ];then
		fix_codeblocks #function
	fi
}

##### main #####
process_args $@ #function
set_directories #function
get_wx_include_dirs #function
gen_project #function
fix_projects #function


